const ServicePosition = require("../../service/service_position.js");

/**
 * 将区域选择相关单独区分开来,以优化可读性
 */
module.exports = Behavior({
  /**
   * 页面的初始数据
   */
  data: {
    b_address_areaSelectShowFlag: false,  // 显示选择区域三级联动弹出框标志
    b_address_resetAreaFlag: false, // 重设区域三级联动内容
  },
  /**
   * 方法
   */
  methods: {
    /**
     * 打开区域选择三级联动弹出框
     */
    b_address_onOpenAreaSelect: function (e) {
      const _this = this;
      //
      _this.setData({
        b_address_areaSelectShowFlag: true,
        b_address_addressEditShowFlag: false
      })
    },
    /**
     * 关闭区域选择三级联动弹出框
     */
    b_address_onCloseAreaSelect: function (e) {
      const _this = this;
      //
      _this.setData({
        b_address_areaSelectShowFlag: false,
        b_address_addressEditShowFlag: true
      })
    },

    /**
     * 显示区域选择省份
     */
    b_address_onShowAreaProvince: function (e) {
      const _this = this;
      ServicePosition.provinceList(data => {
        e.detail.callback(data.records);
      })
    },

    /**
     * 显示区域选择地级市
     */
    b_address_onShowAreaCity: function (e) {
      const _this = this;
      ServicePosition.cityList(e.detail.level1.id, data => {
        e.detail.callback(data.records);
      })
    },
    /**
     * 显示区域选择县级市
     */
    b_address_onShowAreaTown: function (e) {
      const _this = this;
      ServicePosition.townList(e.detail.level2.id, null, data => {
        e.detail.callback(data.records);
      })
    },
    /**
     * 选择区域选择县级市
     */
    b_address_onSelectAreaTown: function (e) {
      const _this = this;
      const province = e.detail.level1;
      const city = e.detail.level2;
      const town = e.detail.level3;
      e.detail.callback();
      //
      const b_address_addressEditData = _this.data.b_address_addressEditData;
      b_address_addressEditData.area = province.name + '/' + city.name + '/' + town.name
      b_address_addressEditData.townId = town.id;
      //
      _this.setData({
        b_address_addressEditData: b_address_addressEditData,
        b_address_areaSelectShowFlag: false,
        b_address_addressEditShowFlag: true
      });
    },
    /**
     * 区域搜索
     */
    b_address_onAreaSearch: function (e) {
      const _this = this;
      ServicePosition.search(e.detail.search.split(" "), function (data) {
        // 转换为所需格式
        const arr = [];
        for (var item of data.records) {
          arr.push({
            level1: { id: item.provinceId, name: item.provinceName },
            level2: { id: item.cityId, name: item.cityName },
            level3: { id: item.id, name: item.name }
          });
        }
        // 回调
        e.detail.callback(arr);
      });
    }
  }

})